package com.example.demo.controller;

import com.google.code.kaptcha.Producer;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @BelongsProject: demo
 * @BelongsPackage: com.example.demo.controller
 * @Author: HUI
 * @CreateTime: 2022-03-11 17:28
 * @Description:
 */

@RestController
public class VerifyCodeController {
    private final Producer producer;


    @Autowired
    public VerifyCodeController(Producer producer) {
        this.producer = producer;
    }

    @GetMapping("/vc.jpg")
    public String getVerifyCode(HttpSession session) {
        //1、生成验证码
        String text = producer.createText();

        //2、放入 session、Redis
        session.setAttribute("kaptcha", text);

        //3、生成图片
        BufferedImage image = producer.createImage(text);
        FastByteArrayOutputStream stream = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", stream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Base64.encodeBase64String(stream.toByteArray());

    }
}
